﻿using System;
using System.IO;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using SerbinAV.Components;

namespace SerbinAV.MobileSales.Sales.Common
{

    public class HandlerException:IHandlerException
    {
        private FileInfo _file;
        public ISaveLoader<String> Saver { get; private set; }

        public HandlerException (ISaveLoader<String> saver, FileInfo file)
        {
            Saver = saver;
            _file = file;
        }

        protected virtual void SaveTofile (string data)
        {
            using (Stream stream = new FileStream(_file.FullName, FileMode.OpenOrCreate))
            {
                Saver.Save(data, stream);
            }
        }

        public void Go(string message, string caption, Exception exception)
        {
            ShowMessage(message, caption, exception);
            StringBuilder sb = new StringBuilder();
            sb.AppendLine(exception.GetType().Name);
            sb.AppendLine(exception.Message);
            sb.AppendLine(exception.StackTrace);
            try
            {
                SaveTofile(sb.ToString());
            }
            catch (Exception)
            {
                
            }
        }

        protected virtual void ShowMessage(string message, string caption, Exception ex)
        {
            if (CustomMessageBox.Show(null, message, caption, new Dictionary<string, DialogResult>(){{"Ok", DialogResult.OK}, {"Details", DialogResult.Yes}}, MessageBoxIcon.Hand ) == DialogResult.Yes)
            {
                TextBox textBox = new TextBox();
                textBox.Multiline = true;
                textBox.Text = ex.GetType().Name  + ex.Message;
                textBox.Dock = DockStyle.Fill;
                Form form = new Form();
                form.MinimizeBox = false;
                form.Controls.Add(textBox);
                form.ShowDialog();
            }
        }
    }
}
